<template>
  <div :class="styles['app-header']">
    <div :class="styles['main-header']">
      <div class="d-flex">
        <router-link to="/" :class="styles['App-logo']">
          <!-- 此处为版权标识，严禁删改 -->
          <img :src="config.resourceUrl?.[Number(config.systemLogo)] || logo" />
        </router-link>
        <div :class="styles['navs']">
          <div v-for="item in navs" :key="item.key" :class="item.key === currentNav ? styles['nav-active-item'] : styles['nav-item']" @click="handleNavClick(item.key)">
            {{ item.label }}
          </div>
        </div>
      </div>
      <div class="d-flex">
        <div v-if="departments.length === 1" :class="styles['department-name']">
          {{ currentDepartment }}
        </div>
        <Dropdown v-else-if="departments.length > 1" :menu="{ items: departmentsMenu, onClick: onDepClick }">
          <div :class="styles['department-name']" style="cursor: pointer">
            {{ currentDepartment }}
          </div>
        </Dropdown>
        <Button.Group :class="styles['button-group']">
          <Dropdown :menu="{ items, onClick }" placement="bottomRight" :trigger="['hover']">
            <div class="d-flex align-items-center" style="cursor: pointer">
              <template v-if="user && user.name">
                <Image :width="36" :height="36" :style="{ borderRadius: '50%', marginTop: '-23px !important' }" :src="user.avatar === -1 ? memberDefaultAvatar : resourceUrl[user.avatar]" :preview="false" />
                <span class="ml-8 c-admin">{{ user.name }}</span>
              </template>
            </div>
            <template #overlay> <Menu :items="items" :onClick="onClick" /> </template>
          </Dropdown>
        </Button.Group>
        <ChangePasswordModel :open="changePasswordVisible" @cancel="changePasswordVisible = false" />
        <UserInfoModel :open="userInfoVisible" @cancel="userInfoVisible = false" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, h } from "vue";
import { useRouter, useRoute } from "vue-router";
import { Modal, Button, Dropdown, Menu, Image } from "ant-design-vue";
import { ExclamationCircleFilled } from "@ant-design/icons-vue";
import { useUserStore, useSystemStore } from "@/stores";
import { setDepKey, setDepName, getDepName, clearToken } from "@/utils";
import ChangePasswordModel from "./ChangePasswordModel";
import UserInfoModel from "./UserInfoModel";
import styles from "./header/index.module.scss";
import logo from "@/assets/logo.png";
import memberDefaultAvatar from "@/assets/thumb/avatar.png";

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const systemStore = useSystemStore();

const changePasswordVisible = ref(false);
const userInfoVisible = ref(false);
const departmentsMenu = ref<any>([]);
const currentDepartment = ref("");
const currentNav = ref(route.path);

const user = computed(() => userStore.user);
const departments = computed(() => userStore.departments);
const config = computed(() => systemStore);
const resourceUrl = computed(() => userStore.resourceUrl);

onMounted(() => {
  if (departments.value.length > 0) {
    currentDepartment.value = getDepName() || departments.value[0].name;
    const arr: any = [
      {
        key: "1",
        type: "group",
        label: "部门",
        children: [],
      },
    ];
    departments.value.map((item: any) => {
      arr[0].children.push({
        key: item.id,
        label: item.name,
        disabled: item.name === currentDepartment.value,
      });
    });
    departmentsMenu.value = arr;
  }
});

watch(
  () => route.path,
  (newPath) => {
    currentNav.value = newPath;
  }
);

const onClick = ({ key }: { key: string | number }) => {
  if (key === "login_out") {
    Modal.confirm({
      title: "操作确认",
      icon: () => h(ExclamationCircleFilled),
      content: "确认退出登录？",
      centered: true,
      okText: "确认",
      cancelText: "取消",
      onOk() {
        userStore.logoutAction();
        window.location.href = "/login";
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  } else if (key === "change_password") {
    changePasswordVisible.value = true;
  } else if (key === "user_info") {
    userInfoVisible.value = true;
  }
};

const items = [
  {
    label: "个人信息",
    key: "user_info",
    icon: () => h("i", { class: "iconfont icon-icon-12 c-red", style: { fontSize: 16 } }),
  },
  {
    label: "修改密码",
    key: "change_password",
    icon: () => h("i", { class: "iconfont icon-icon-password c-red", style: { fontSize: 16 } }),
  },
  {
    label: "退出登录",
    key: "login_out",
    icon: () => h("i", { class: "iconfont icon-a-icon-logout c-red", style: { fontSize: 16 } }),
  },
];

const onDepClick = ({ key }: { key: string | number }) => {
  let name = "";
  departments.value.map((item: any) => {
    if (Number(key) === item.id) {
      name = item.name;
    }
  });
  Modal.confirm({
    title: "操作确认",
    icon: () => h(ExclamationCircleFilled),
    content: "确认切换部门？",
    centered: true,
    okText: "确认",
    cancelText: "取消",
    onOk() {
      currentDepartment.value = name;
      userStore.saveCurrentDepId(Number(key));
      setDepKey(String(key));
      setDepName(name);
      const box = [...departments.value];
      const arr: any = [
        {
          key: "1",
          type: "group",
          label: "部门",
          children: [],
        },
      ];
      box.map((item: any) => {
        arr[0].children.push({
          key: item.id,
          label: item.name,
          disabled: item.name === name,
        });
      });
      departmentsMenu.value = arr;
    },
    onCancel() {
      console.log("Cancel");
    },
  });
};

const navs = [
  {
    key: "/",
    label: "首页",
  },
  {
    key: "/latest-learn",
    label: "最近学习",
  },
];

const handleNavClick = (key: string) => {
  currentNav.value = key;
  router.push(key);
};
</script>
